package com.violet.auth.client.util;

import com.violet.auth.client.token.CustomWebAuthenticationDetails;
import com.violet.common.constant.universal.SecurityConstants;
import com.violet.common.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;

import java.util.Map;

/**
 * 类说明: 认证授权相关工具类
 *
 * @author wqf
 * @date 2024/8/30 16:35
 */
@Slf4j
public class AuthUtils {

    /**
     * 获取登陆的用户名
     */
    public static String getUsername(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof LoginUser) {
            username = ((LoginUser) principal).getUsername();
        } else if (principal instanceof String) {
            username = (String) principal;
        }
        return username;
    }

    /**
     * 获取登陆的帐户类型
     */
    @SuppressWarnings("unchecked")
    public static String getAccountType(Authentication authentication) {
        String accountType = null;
        if (authentication != null) {
            Object details = authentication.getDetails();
            if (details != null) {
                if (details instanceof CustomWebAuthenticationDetails detailsObj) {
                    accountType = detailsObj.getAccountType();
                } else {
                    Map<String, String> detailsMap = (Map<String, String>) details;
                    accountType = detailsMap.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
                }
            }
        }
        return accountType;
    }
}